/*
 * @Author: Ryan Huang
 * @Date: 2019-04-03 21:35:13
 * @Description: 聊天室的服务器
 */
package main

import (
	"encoding/json"
	"my/homework/chatroom/model"
	"net"
)

func main() {
	laddr, _ := net.ResolveUDPAddr("udp", ":8888")
	conn, _ := net.ListenUDP("udp", laddr)
	defer conn.Close()
	names := make(map[string]string)
	for {
		buffer := make([]byte, 4096)
		n, remoteAddr, _ := conn.ReadFromUDP(buffer)
		var msg model.Msg
		json.Unmarshal(buffer[:n], &msg)
		if _, ok := names[remoteAddr.String()]; !ok {
			names[remoteAddr.String()] = msg.Header.Name
		}
		conn.WriteToUDP(buffer[:n], remoteAddr)
		for addr, _ := range names {
			if addr == remoteAddr.String() {
				continue
			}
			addrPtr, _ := net.ResolveUDPAddr("udp", addr)
			conn.WriteToUDP(buffer[:n], addrPtr)
		}
	}
}
